import React from "react";
import { useRequest } from "ahooks";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Heading } from "@/components/ui/heading";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { zodResolver } from "@hookform/resolvers/zod";
import { ColumnDef, createColumnHelper } from "@tanstack/react-table";
import { ArrowUpDown } from "lucide-react";
import { Edit, MoreHorizontal, Trash } from "lucide-react";
import { useSearchParams } from "react-router-dom";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { AlertModal } from "@/components/modal/alert-modal";
import { TenantI } from "@/types";
import PageContainer from "@/components/layout/page-container";
import CustomDndTable from "@/components/ui/custom-dnd-table";
import { useToast } from "@/hooks/use-toast";
import { Plus } from "lucide-react";
import {
  createTenant,
  updateTenant,
  searchTenantList,
  deleteTenant,
} from "@/api";
import { Loading } from "@/components/ui/loading";

const formSchema = z.object({
  id: z.string().optional(),
  name: z.string().trim().min(3, { message: "中心名称至少3个字符" }),
  description: z.string().trim().min(3, { message: "描述信息至少3个字符" }),
});

type FormValuesT = z.infer<typeof formSchema>;

const page: React.FC = () => {
  const [searchParams] = useSearchParams();
  const { toast } = useToast();

  const [title, setTitle] = React.useState<string>("");
  const [description, setDescription] = React.useState<string>("");
  const [isSubmitting, setIsSubmitting] = React.useState<boolean>(false);
  const [isAlertOpen, setIsAlertOpen] = React.useState<boolean>(false);
  const [isDialogOpen, setIsDialogOpen] = React.useState<boolean>(false);
  const [totalCount, setTotalCount] = React.useState<number>(0);
  const [tenantList, setTenantList] = React.useState<TenantI[]>([]);
  const [formData, setFormData] = React.useState<TenantI>();

  const { loading, run } = useRequest(
    (paramsString: string) => searchTenantList(paramsString),
    {
      manual: true,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp, params: any) {
        // console.log(params);
        setTenantList(resp.data.data);
        setTotalCount(resp.data.totalCount);
      },
      onError(e: any, params: any) {
        console.error("获取数据失败");
        toast({
          variant: "destructive",
          title: "数据获取失败",
          description: "请检查网络或联系系统管理员",
        });
      },
    }
  );

  const onUpdateClick = (event: any, data: TenantI) => {
    setTitle("修改中心");
    form.reset(data);
    setIsDialogOpen(true);
    run(searchParams.toString());
  };

  const onDeleteConfirm = (event: any, data: TenantI) => {
    try {
      setIsSubmitting(true);
      if (data.id) {
        deleteTenant(data.id).then(
          (res: any) => {
            console.log(data);
            console.log(res);
            toast({
              title: "删除成功",
              description: "",
            });
            run(searchParams.toString());
          },
          (err: any) => {
            toast({
              title: "删除失败",
              description: "error",
            });
          }
        );
      }
    } catch (error: any) {
      console.log(error);
      toast({
        title: "删除失败",
        description: "error",
      });
    } finally {
      setIsSubmitting(false);
      setIsAlertOpen(false);
    }
  };

  const columnHelper = createColumnHelper<TenantI>();
  const columns = [
    columnHelper.display({
      id: "select",
      header: (props) => {
        // console.log(props);
        if (props && props.table) {
          return (
            <Checkbox
              checked={props.table.getIsAllPageRowsSelected()}
              onCheckedChange={(value) =>
                props.table.toggleAllPageRowsSelected(!!value)
              }
              aria-label="Select all"
            />
          );
        } else {
          return <Checkbox aria-label="Select all" />;
        }
      },
      footer: (props) => props.column.id,
      cell: (props) => {
        console.log(props);
        if (props && props.row) {
          return (
            <Checkbox
              checked={props.row.getIsSelected()}
              onCheckedChange={(value) => props.row.toggleSelected(!!value)}
              aria-label="Select row"
            />
          );
        } else {
          return <Checkbox aria-label="Select row" />;
        }
      },
      enableSorting: false,
      enableHiding: true,
    }),
    columnHelper.accessor("id", {
      id: "id",
      header: "ID",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return <span>{row.getValue("id")}</span>;
        }
      },
      enableSorting: true,
      enableHiding: false,
    }),
    columnHelper.accessor("name", {
      id: "name",
      header: "中心名称",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return <span>{row.getValue("name")}</span>;
        }
      },
      enableSorting: true,
      enableHiding: false,
    }),
    columnHelper.display({
      id: "actions",
      header: "操作",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <>
              <AlertModal
                isOpen={isAlertOpen}
                onClose={() => setIsAlertOpen(false)}
                onConfirm={() => onDeleteConfirm(event, row.original)}
                loading={loading}
              />
              <DropdownMenu modal={false}>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="h-8 w-8 p-0">
                    <span className="sr-only">选项</span>
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel></DropdownMenuLabel>
                  <DropdownMenuItem
                    onClick={() => onUpdateClick(event, row.original)}
                  >
                    <Edit className="mr-2 h-4 w-4" /> 更新
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setIsAlertOpen(true)}>
                    <Trash className="mr-2 h-4 w-4" /> 删除
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </>
          );
        }
      },
    }),
  ];

  const defaultValues = {
    id: undefined,
    name: "",
  };

  // 表单部分
  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
  });

  const onFormSubmit = async (data: FormValuesT) => {
    try {
      setIsSubmitting(true);
      if (data.id) {
        updateTenant(data).then(
          (res) => {
            console.log(res);
            run(searchParams.toString());
          },
          (err) => {
            toast({
              variant: "destructive",
              title: "数据提交失败",
              description: "请检查网络或联系系统管理员",
            });
          }
        );
      } else {
        createTenant(data).then(
          (res) => {
            console.log(res);
            run(searchParams.toString());
          },
          (err) => {
            toast({
              variant: "destructive",
              title: "数据提交失败",
              description: "请检查网络或联系系统管理员",
            });
          }
        );
      }
      setIsSubmitting(false);
      setIsDialogOpen(false);
      form.reset(defaultValues);
      toast({
        variant: "success",
        title: "数据提交成功",
        description: "",
        duration: 1600,
      });
    } catch (error: any) {
      toast({
        variant: "destructive",
        title: "数据提交失败",
        description: "请检查网络或联系系统管理员",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  React.useEffect(() => {
    // console.log(searchParams.toString());
    run(searchParams.toString());
  }, [searchParams]);

  return (
    <PageContainer>
      <div className="space-y-4">
        {/* <Breadcrumbs items={breadcrumbItems} /> */}

        <div className="flex items-start justify-between">
          <Heading
            title={`中心列表`}
            description="每个中心对应不同的用户组和权限"
          />

          <Button
            variant="outline"
            className="p-2 rounded-md"
            onClick={() => {
              form.reset(defaultValues);
              setTitle("创建中心");
              setIsDialogOpen(!isDialogOpen);
            }}
          >
            <Plus className="mr-2 h-4 w-4" />
            创建
          </Button>
        </div>
        <Separator />

        <CustomDndTable
          defaultFilterColumn="name"
          columns={columns}
          initColumnVisibility={{ select: false }}
          totalCount={totalCount}
          loading={loading}
          data={tenantList}
        />

        <Dialog
          open={isDialogOpen}
          onOpenChange={() => setIsDialogOpen(!isDialogOpen)}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle></DialogTitle>
              <DialogDescription></DialogDescription>
            </DialogHeader>
            <div className="flex items-center justify-between">
              <Heading title={title} description={description} />
            </div>
            <Separator />
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onFormSubmit)}
                className="w-full space-y-8"
              >
                {/* <div className="gap-8 md:grid md:grid-cols-3"> */}
                <div className="flex flex-col gap-4">
                  {formData && formData.id ? (
                    <FormField
                      control={form.control}
                      name="id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>ID</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="id"
                              {...field}
                              disabled={formData && formData.id ? true : false}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  ) : null}
                  <FormField
                    control={form.control}
                    name="name"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>中心名称</FormLabel>
                        <FormControl>
                          <Input
                            disabled={loading}
                            placeholder="Tenant name"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="description"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>描述</FormLabel>
                        <FormControl>
                          <Textarea
                            disabled={loading}
                            placeholder="Tenant description"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <Button disabled={loading} className="ml-auto" type="submit">
                  提交
                </Button>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>
    </PageContainer>
  );
};

export default page;
